package com.example.androidmaps;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;


public class CloudHelper {
	public final String CLOUD = "http://softeng.cs.uwosh.edu/students/cs342g1/";
	public final String FILE_NAME = "CloudZip.gz";
	public final String FILE_LOCATION = "/data/data/" + FILE_NAME;
	public static int bufferSize = 1024;
	
	public boolean CheckUsernameExists(String username){
		String result = "empty";
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "CheckUsernameExists.php");

		String xml = "<node><username>" + username + "</username></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);
            
            
            NodeList nl = doc.getElementsByTagName("loginMessage");
            for(int i = 0; i < nl.getLength(); i++) {
                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
                     result = nameElement.getFirstChild().getNodeValue().trim();
                 }
            }

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(result.equals("failure")){
			return false;
		}else{
			return true;
		}
	}
	
	public int InsertNewUser(String username, String hashedPW, String salt){
		int result = -1;
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "InsertNewUser.php");

		String xml = "<node><username>" + username + "</username><password>" + hashedPW + "</password><salt>" + salt + "</salt></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);
            
            
            NodeList nl = doc.getElementsByTagName("insertId");
            for(int i = 0; i < nl.getLength(); i++) {
                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
                     result = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
                 }
            }

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(result);
		return result;
	}
	
	public int CheckUsernamePasswordValid(String username, String password){
		int userId = -1;
		String user = "";
		String pw = "";
		String salt = "";
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "GetUsernamePasswordSalt.php");

		String xml = "<node><username>" + username + "</username></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);
            
            
            NodeList nl = doc.getElementsByTagName("u");
            for(int i = 0; i < nl.getLength(); i++) {
                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
                     user = nameElement.getFirstChild().getNodeValue().trim();
                 }
            }
            NodeList n2 = doc.getElementsByTagName("p");
            for(int i = 0; i < n2.getLength(); i++) {
                if (n2.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n2.item(i);
                     pw = nameElement.getFirstChild().getNodeValue().trim();
                 }
            }
            NodeList n3 = doc.getElementsByTagName("s");
            for(int i = 0; i < n3.getLength(); i++) {
                if (n3.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n3.item(i);
                     salt = nameElement.getFirstChild().getNodeValue().trim();
                 }
            }
            NodeList n4 = doc.getElementsByTagName("i");
            for(int i = 0; i < n4.getLength(); i++) {
                if (n4.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) n4.item(i);
                     userId = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
                 }
            }

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch(Exception e){
			return -1;
		}
		String newPw = PasswordHasher.md5(password + salt);
		boolean same = newPw.equalsIgnoreCase(pw);
		
		return (same ? userId : -1);
	}
	
	public void InsertNewCurrentLocation(double cloudId, double lon, double lat){
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "InsertNewCurrentLocation.php");

		String xml = "<node><cloudId>" + cloudId + "</cloudId><lon>" + lon + "</lon><lat>" + lat + "</lat></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public int InsertFavoritePlace(String cloudId, String lon, String lat, String place){
		place = place.replace("'", "\\'");
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "InsertFavoritePlace.php");
        int insertId = -1;
		String xml = "<node><cloudId>" + cloudId + "</cloudId><lon>" + lon + "</lon><lat>" + lat + "</lat><place>" + place + "</place></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);

            NodeList nl = doc.getElementsByTagName("insertId");
            for(int i = 0; i < nl.getLength(); i++) {
                if (nl.item(i).getNodeType() == org.w3c.dom.Node.ELEMENT_NODE) {
                     org.w3c.dom.Element nameElement = (org.w3c.dom.Element) nl.item(i);
                     insertId = Integer.parseInt(nameElement.getFirstChild().getNodeValue().trim());
                 }
            }
            
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return insertId;
	}
	
	public void UpdateCurrentLocation(double cloudId, double lon, double lat){
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "UpdateCurrentLocation.php");

		String xml = "<node><cloudId>" + cloudId + "</cloudId><lon>" + lon + "</lon><lat>" + lat + "</lat></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
            String xmlString = EntityUtils.toString(responseEntity);
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(xmlString));
            Document doc = db.parse(inStream);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void sendFriendRequest(String toId,String fromId){
		String result = "empty";
		HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(CLOUD + "SendFriendRequest.php");

		String xml = "<node><fromId>" + fromId + "</fromId>+<toId>" + toId + "</toId></node>";
		try {
			StringEntity entity = new StringEntity(xml, "UTF-8");
			httppost.setEntity(entity); 
            httppost.addHeader("Accept", "application/xml");
            httppost.addHeader("Content-Type", "application/xml");
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity responseEntity= response.getEntity();
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
